﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.VisualBasic.FileIO;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class PrdPerformanceInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public PrdPerformanceInterfaceBusiness()
        {
            this.InterfaceName = "领星产品表现";
            //获取字段的映射关系
            tableField = GetMapField("addRow");
            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();
            //Filters.Add(
            //    //13:>,14>=15:<,16<=
            //    new OL_FilterDTO() { ControlId = "673b17917d6d0d88187c53a4", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") }//FDATE字段过滤日开始700天前到现在的数据
            //);

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //当前时间不能为凌晨0点，否则会出现跨天查询会有问题
            if (DateTime.Now.ToString("HH") != "00")
            {
                try
                {
                    //数据库连接
                    ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                    SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                    //获取此接口的所有API信息
                    this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                    Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                    Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                    Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                    Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

                    //获取One_Link亚马逊MSKU信息
                    AMZ_MSKUInterfaceBusiness aMZ_MSKU = new AMZ_MSKUInterfaceBusiness();
                    aMZ_MSKU.Filters.Clear();
                    aMZ_MSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 2, SpliceType = 1, FilterType = 14, Value = "" }//只查询亚马逊的MSKU
           );
                    List<AMZ_MSKU> AMZ_MSKUList = await aMZ_MSKU.QueryAsync<AMZ_MSKU>(aMZ_MSKU.queryOption, aMZ_MSKU.tableField, aMZ_MSKU.SqlDb);
                    foreach (var item1 in AMZ_MSKUList)
                    {
                        //SKU
                        List<AssTable> table = item1.sku_lock.ToObject<List<AssTable>>();
                        if (!table.IsNullOrEmpty() && table.Count > 0)
                        {
                            item1.sku_lock_T = table[0];
                            item1.sku_lock = item1.sku_lock_T.sid;
                        }
                        else
                        {
                            item1.sku_lock = "";
                        }
                    }


                    //获取源数据
                    LX_PrdPerformanceInterfaceBusiness LX_PrdPerformance = new LX_PrdPerformanceInterfaceBusiness();
                    List<PrdPerformance> sourceData = await LX_PrdPerformance.QueryAsync<PrdPerformance>(LX_PrdPerformance.LX_Query, SqlDb);

                    //筛选销量，退货量，退款量，销售额，广告费，促销折扣，广告销售额不等于0的
                    sourceData = sourceData.Where(x => (x.volume.ToDouble() != 0 && !x.volume.IsNullOrEmpty())
                    || (x.return_goods_count.ToDouble() != 0 && !x.return_goods_count.IsNullOrEmpty())
                    || (x.return_count.ToDouble() != 0 && !x.return_count.IsNullOrEmpty())
                    || (x.amount.ToDouble() != 0 && !x.amount.IsNullOrEmpty())
                    || (x.spend.ToDouble() != 0 && !x.spend.IsNullOrEmpty())
                    || (x.promotion_discount.ToDouble() != 0 && !x.promotion_discount.IsNullOrEmpty())
                    || (x.ad_sales_amount.ToDouble() != 0) && !x.ad_sales_amount.IsNullOrEmpty()).ToList();
                    AddLog(SqlDb, $"过滤操作成功，查询总条数{sourceData.Count}", InterfaceName, "LX_Query", "");
                    //每天美元的汇率
                    List<PrdPerformance> dollarList = sourceData.Where(x =>
                    {
                        //国家，价格信息不为空的
                        if (!x.price_list.IsNullOrEmpty() && !x.price_list.IsNullOrEmpty() && x.price_list[0].country == "美国") return true;
                        else return false;
                    }).GroupBy(x => x.date).Select(x => x.First()).ToList();

                    double rate = 0;
                    double rate_dollar_today = 0.0;
                    double amount_s = 0;
                    //ID，字段赋值
                    foreach (var item1 in sourceData)
                    {
                        // 父asin
                        if (!item1.parent_asins.IsNullOrEmpty()) item1.parent_asin = item1.parent_asins[0].parent_asin;
                        // asin列表
                        if (!item1.asins.IsNullOrEmpty()) item1.asin = item1.asins[0].asin;
                        // 价格列表
                        if (!item1.price_list.IsNullOrEmpty())
                        {
                            item1.country = item1.price_list[0].country;
                            item1.is_eur = item1.price_list[0].is_eur;
                            item1.local_sku = item1.price_list[0].local_sku;
                            item1.mid = item1.price_list[0].mid;
                            item1.local_name_asin = item1.price_list[0].local_name;
                            item1.is_delete = item1.price_list[0].is_delete;
                            item1.volume_asin = item1.price_list[0].volume;
                            item1.seller_name_asin = item1.price_list[0].seller_name;
                            item1.price = item1.price_list[0].price;
                            item1.seller_sku = item1.price_list[0].seller_sku;
                            item1.status = item1.price_list[0].status;
                            item1.cid = item1.price_list[0].cid;
                            item1.sid = item1.price_list[0].sid;
                            //获取汇率
                            rate = item1.price_list[0].source_rate.ToDouble();
                            item1.source_rate = rate.ToString("F6"); ;
                        }
                        //小类排名
                        if (!item1.small_cate_rank.IsNullOrEmpty())
                        {
                            item1.category = item1.small_cate_rank[0].category;
                            item1.prev_rank = item1.small_cate_rank[0].prev_rank;
                            item1.rank = item1.small_cate_rank[0].rank;
                        }
                        //店铺/国家
                        if (!item1.seller_store_countries.IsNullOrEmpty()) item1.seller_name = item1.seller_store_countries[0].seller_name;
                        //分类
                        if (!item1.categories.IsNullOrEmpty()) item1.categorie = item1.categories[0];
                        //品牌
                        if (!item1.brands.IsNullOrEmpty()) item1.brand = item1.brands[0];
                        //负责人
                        if (!item1.principal_names.IsNullOrEmpty()) item1.principal_name = item1.principal_names[0];
                        //开发人
                        if (!item1.developer_names.IsNullOrEmpty()) item1.developer_name = item1.developer_names[0];
                        //供应商，sku维度特有
                        if (!item1.suppliers.IsNullOrEmpty()) item1.supplier = item1.suppliers[0];
                        //型号，sku维度特有	
                        if (!item1.model.IsNullOrEmpty()) item1.model_ = item1.model[0];
                        item1.ID = item1.seller_sku + item1.date + item1.seller_name;

                        //获取当日美元的汇率
                        var o = dollarList.Where(x => x.date == item1.date).ToList();

                        if (!o.IsNullOrEmpty() && o.Count() > 0) rate_dollar_today = o.First().price_list[0].source_rate.ToDouble();

                        //广告销售额$
                        if (!item1.ad_sales_amount.IsNullOrEmpty() && item1.country != "美国")
                        {
                            amount_s = item1.ad_sales_amount.ToDouble();
                            //原币*本位币汇率/美元汇率
                            item1.ad_sales_amount_dollar = (amount_s * rate / rate_dollar_today).ToString("F2");
                        }
                        else if (!item1.ad_sales_amount.IsNullOrEmpty() && item1.country == "美国")
                        {
                            amount_s = item1.ad_sales_amount.ToDouble();
                            item1.ad_sales_amount_dollar = amount_s.ToString("F2");
                        }
                        else
                        {
                            item1.ad_sales_amount_dollar = "0";
                        }
                        //销售额$
                        if (!item1.amount.IsNullOrEmpty() && item1.country != "美国")
                        {
                            amount_s = item1.amount.ToDouble();
                            //原币*本位币汇率/美元汇率
                            item1.amount_dollar = (amount_s * rate / rate_dollar_today).ToString("F2");
                        }
                        else if (!item1.amount.IsNullOrEmpty() && item1.country == "美国")
                        {
                            amount_s = item1.amount.ToDouble();
                            item1.amount_dollar = amount_s.ToString("F2");
                        }
                        else
                        {
                            item1.amount_dollar = "0";
                        }
                        //促销折扣$
                        if (!item1.promotion_discount.IsNullOrEmpty() && item1.country != "美国")
                        {
                            amount_s = item1.promotion_discount.ToDouble();
                            //原币*本位币汇率/美元汇率
                            item1.promotion_discount_dollar = (amount_s * rate / rate_dollar_today).ToString();
                        }
                        else if (!item1.promotion_discount.IsNullOrEmpty() && item1.country == "美国")
                        {
                            amount_s = item1.promotion_discount.ToDouble();
                            item1.promotion_discount_dollar = amount_s.ToString("F2");
                        }
                        else
                        {
                            item1.promotion_discount_dollar = "0";
                        }
                        //广告花费$
                        if (!item1.spend.IsNullOrEmpty() && item1.country != "美国")
                        {
                            amount_s = item1.spend.ToDouble();
                            //原币*本位币汇率/美元汇率
                            item1.spend_dollar = (amount_s * rate / rate_dollar_today * -1).ToString("F2");
                        }
                        else if (!item1.spend.IsNullOrEmpty() && item1.country == "美国")
                        {
                            amount_s = item1.spend.ToDouble() * -1;
                            item1.spend_dollar = amount_s.ToString("F2");
                        }
                        else
                        {
                            item1.spend_dollar = "0";
                        }
                        //ACOS$
                        if (item1.amount_dollar.IsNullOrEmpty() || item1.spend_dollar.IsNullOrEmpty() || item1.amount_dollar.ToDouble() == 0 || item1.spend_dollar.ToDouble() == 0 || item1.spend_dollar == "-0")
                        {
                            //原币*本位币汇率/美元汇率
                            item1.OL_ACOS = "0";
                        }
                        else
                        {
                            item1.OL_ACOS = (item1.spend_dollar.ToDouble() / item1.amount_dollar.ToDouble()).ToString("F4");
                        }



                        var msku = AMZ_MSKUList.Where(x => x.seller_sku == item1.seller_sku && x.sid == item1.sid);

                        if (!msku.IsNullOrEmpty() && msku.Count() > 0)
                        {
                            item1.OL_MSKU = msku.First().RowId;
                            item1.OL_SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                        }
                        else
                        {
                            item1.OL_MSKU = "";
                            item1.OL_SKU = "";
                        }
                    }



                    //ID赋值
                    //foreach (var item1 in sourceData)
                    //{
                    //    //item1.ID = item1.amazonOrderId + item1.msku;
                    //    item1.source_rate= item1.source_rate.ToDouble().ToString("F6");
                    //}
                    //ID重复项
                    //var t = sourceData.GroupBy(x => x.ID).Where(x => x.Count() > 1);
                    //获取最大时间和最小时间查询源数据
                    var date = sourceData.OrderBy(x => x.date.ToDateTime()).ToList();
                    Filters.Clear();
                    this.Filters.Add(
                   //13:>,14>=15:<,16<=
                   new OL_FilterDTO() { ControlId = "67615b3c9e0bc69bf1b88a9b", DataType = 15, SpliceType = 1, FilterType = 14, Value = date[0].date.ToDateTime().ToString("yyyy-MM-dd") }
               );
                    this.Filters.Add(
                   //13:>,14>=15:<,16<=
                   new OL_FilterDTO() { ControlId = "67615b3c9e0bc69bf1b88a9b", DataType = 15, SpliceType = 1, FilterType = 16, Value = date[sourceData.Count - 1].date.ToDateTime().ToString("yyyy-MM-dd") }
               );
                    //获取目标数据
                    List<PrdPerformance> targetData = new List<PrdPerformance>();//目标据集合
                    targetData = await QueryAsync<PrdPerformance>(queryOption, tableField, SqlDb);
                    if (this.State > 0 && sourceData.Count > 0)
                    {
                        //更新
                        #region
                        List<PrdPerformance> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<PrdPerformance>(Keys, "RowId")).ToList();//获取交集(更新项)
                        List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                        ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                        #endregion

                        //新增
                        #region

                        List<PrdPerformance> insertItem = sourceData.Except(targetData, new ComparerFromKey<PrdPerformance>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                        List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                        ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                        #endregion

                        //删除
                        #region
                        List<PrdPerformance> deleteItem = targetData.Except(sourceData, new ComparerFromKey<PrdPerformance>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)

                        List<PrdPerformance> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        //将重复的项也一起加入删除的列表
                        deleteItem.AddRange(repeatItem);
                        //筛选出删除列表中重复的项
                        var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        deleteItem.AddRange(temp);

                        List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                        ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                        #endregion

                        //同步数据库
                        SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                        sqlDBInterface.ExecuteInterface<PrdPerformance>(sourceData, "SD_LX_PrdPerformance", $"WHERE date >= '{date[0].date.ToDateTime().ToString("yyyy-MM-dd")}' AND date<='{date[sourceData.Count - 1].date.ToDateTime().ToString("yyyy-MM-dd")}'");
                    }
                    else
                    {
                        throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                    }
                }
                catch (Exception ex)
                {
                    AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                }


            }
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
